'use strict'

let userDao = require('../dao/userDao')
let uuid = require('uuid')
let nodeSessionMgr = require('./nodeSessionMgr')
let route = require('./route')
let Token = {}
let userServerConfig = require('../config').userServerConfig



  //用户注册
route.setNotLogin('createUser', function(session, msg, next) {
  let username = msg.username
  let password = msg.password

  if (!/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(username) || !/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(password)) {
    next(1)
    return
  }
  //判断名字是否已经存在
  userDao.getUserByUsername(username, function(err, res) {
    if (err || res) { //名字已经存在
      next(2)
      return
    }
    userDao.newAndSave(username, password, function(err) {
      if (err) {
        next(3)
        return
      }
      next(0)
    })
  })
})

//用户登陆
route.setNotLogin('userLogin', function(session, msg, next) {
  let username = msg.username
  let password = msg.password
  if (!/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(username) || !/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(password)) {
    next(1)
    return
  }
  //判断是否已经存在
  userDao.getUserByQuery({
    username: username,
    password: password
  }, function(err, res) {
    if (err || !res) {
      next(2)
      return
    }
    next({
      error: 0,
      userId: res._id
    })
  })
})

//验证令牌
route.setNotLogin('verifyUser', function(session, msg, next) {
  let username = msg.username
  let password = msg.password
  if (!/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(username) || !/^([a-z]|[A-Z]|[0-9]){3,16}$/.test(password)) {
    next(1)
    return
  }
  //判断是否已经存在
  userDao.getUserByQuery({
    username: username,
    password: password
  }, function(err, res) {
    if (err || !res) {
      next(2)
      return
    }
    next({
      error:0,
      userId: res._id
    })
  })
})
